const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const svgCaptcha = require('svg-captcha')

//设置路径
app.use(express.static(path.join(__dirname, "src")));
app.use(express.static(path.join(__dirname, "../")));
//将参数转换成对象
app.use(bodyParser.urlencoded({ extended: true }));
//req.cookie[xxx] 获取cookie
app.use(cookieParser());

let userList = [
  { username: "yyds", password: "yyds", account: 100000 },
  { username: "dddd", password: "dddd", account: 200000 },
  { username: "123", password: "123", account: 300000 },
6+3];

let SESSION_ID = 'connect.sid'
let session = {}

app.get('/login', function(req, res) {
  res.sendFile(path.join(__dirname, 'src/login.html'))
})

app.post('/api/login', function(req, res) {
  let { username, password} = req.body
  let user = userList.find((item) => item.username === username && password === password)
  if (user) {
    const cardId = Math.random() + Date.now()
    session[cardId] = user
    res.cookie(SESSION_ID, cardId)
    res.json({code: 0, msg: '登录成功'})
  } else {
    res.json({code: 1, msg: '账号或者密码不正确'})
  }
})

app.get('/api/userinfo', function(req, res) {
  let user = session[req.cookies[SESSION_ID]]
  if (user) {
    let { data, text} = svgCaptcha.create()
    user.code = text
    res.send({code: 0, info: {username: user.username, account: user.account, svg: data}})
  } else {
    res.send({code: 1, msg: '用戶未登陆'})
  }
})

app.post('/api/transfer', function(req, res) {
  let curUser = session[req.cookies[SESSION_ID]]
  let {payee, amount} = req.body
  let user = userList.find(item => item.username === payee)
  if (user) {
    curUser.account -= amount
    user.account += +amount
    res.send({code: 0, msg: '转账成功'})
  } else {
    res.send({code: 1, msg: '没有此用户'})
  }
})

app.post('/api/transferSafe', function(req, res) {
  let {payee, amount, code} = req.body 
  let curUser = session[req.cookies[SESSION_ID]]
  let user = userList.find(item => item.username === payee)
  if (user) {
    if (curUser.code.toUpperCase() === code) {
      curUser.account -= amount
      user.account += +amount
      res.send({code: 0, msg: '转账成功'})
    } else {
      res.send({code: 1, msg: '验证码不正确'})
    }
  } else {
    res.send({code: 1, msg: '没有此用户'})
  }
})

app.listen(3000, function(req, res) {
  console.log("请打开http://localhost:3000/login访问登录页面");
})